<script setup>
import { ref, onMounted, watch } from 'vue'
import { teamApi } from '@/api/request'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'

// ===== 状态管理 =====
// 团队相关状态
const teams = ref([])
const teamInfo = ref({
  teamname: '',
  createTime: '',
  memberCount: 0,
  description: ''
})
const showEditForm = ref(false)
const editDescription = ref('')

// 搜索相关状态
const searchProject = ref('')
const searchTeam = ref('')
const loading = ref(false)

// 分页相关状态
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)

// ===== 验证规则 =====
// 输入验证规则
const validateInput = (value) => {
  if (!value) return true // 允许为空
  const pattern = /^[\u4e00-\u9fa5a-zA-Z0-9]{2,15}$/
  if (!pattern.test(value)) {
    ElMessage.warning('输入内容只能包含中文、字母和数字，长度在2-15个字符之间')
    return false
  }
  return true
}

// ===== 方法定义 =====
// 处理输入变化
const handleInputChange = (value, type) => {
  if (value && !validateInput(value)) {
    if (type === 'project') {
      searchProject.value = searchProject.value.slice(0, 15)
    } else {
      searchTeam.value = searchTeam.value.slice(0, 15)
    }
    return false
  }
  return true
}

// 获取团队实验列表
const fetchTeamExperiments = async () => {
  loading.value = true
  try {
    const response = await teamApi.getTeamExperiments({
      current: currentPage.value,
      pageSize: pageSize.value,
      experimentName: searchProject.value,
      teamname: searchTeam.value
    })

    if (response.data.code === 200) {
      const responseData = response.data.data || {}
      teams.value = (responseData.records || []).map((item) => ({
        ...item,
        total: item.total || 0,
        experimentName: item.experimentName || '无',
        teamname: item.teamname || '无'
      }))
      total.value = responseData.total || 0
    } else {
      ElMessage.error(response.data.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取团队实验列表失败:', error)
    ElMessage.error('获取团队实验列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 分页处理方法
const handleCurrentChange = (val) => {
  currentPage.value = val
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

// 团队信息编辑方法
const updateTeamInfo = async () => {
  try {
    const response = await teamApi.updateTeamInfo(teamInfo.value.teamname, {
      description: editDescription.value
    })
    if (response.data.code === 200) {
      await fetchTeamExperiments()
      showEditForm.value = false
      ElMessage.success('更新成功')
    } else {
      ElMessage.error(response.data.message || '更新失败')
    }
  } catch (error) {
    console.error('更新团队信息失败:', error)
    ElMessage.error('更新团队信息失败，请稍后重试')
  }
}

const handleEdit = (row) => {
  teamInfo.value = { ...row }
  editDescription.value = row.description
  showEditForm.value = true
}

// ===== 监听器 =====
watch(
  [searchProject, searchTeam, currentPage, pageSize],
  ([newProject, newTeam]) => {
    if (
      handleInputChange(newProject, 'project') &&
      handleInputChange(newTeam, 'team')
    ) {
      fetchTeamExperiments()
    }
  }
)

// ===== 生命周期钩子 =====
onMounted(() => {
  fetchTeamExperiments()
})
</script>

<template>
  <div class="team-info-container">
    <div class="header">
      <div class="left">
        <h2 class="title">团队基本信息</h2>
      </div>
    </div>

    <div class="search-container">
      <div class="search-item">
        <span class="search-label">团队名称：</span>
        <el-input
          v-model="searchTeam"
          placeholder="请输入团队名称"
          clearable
          class="search-input"
          maxlength="15"
          @input="(value) => handleInputChange(value, 'team')"
          :show-word-limit="true"
        />
      </div>
      <div class="search-item">
        <span class="search-label">检测项目：</span>
        <el-input
          v-model="searchProject"
          placeholder="请输入检测项目"
          clearable
          class="search-input"
          maxlength="15"
          @input="(value) => handleInputChange(value, 'project')"
          :show-word-limit="true"
        />
      </div>
    </div>

    <div class="team-list">
      <el-table
        :data="teams"
        stripe
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="teamname" label="团队名称" />
        <el-table-column prop="experimentName" label="检测项目" />
        <el-table-column align="right" width="100">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog
      v-model="showEditForm"
      title="编辑团队信息"
      width="500px"
      destroy-on-close
    >
      <el-form>
        <el-form-item label="团队描述">
          <el-input
            v-model="editDescription"
            type="textarea"
            :rows="4"
            placeholder="请输入团队描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showEditForm = false">取消</el-button>
          <el-button type="primary" @click="updateTeamInfo">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.team-info-container {
  padding: 32px;
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(115, 103, 240, 0.08);
}

.header {
  margin-bottom: 32px;

  .title {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
    color: #1e1e2d;
    position: relative;

    &::after {
      content: '';
      position: absolute;
      bottom: -8px;
      left: 0;
      width: 40%;
      height: 2px;
      background: linear-gradient(90deg, #7367f0 0%, transparent 100%);
    }
  }
}

.search-container {
  display: flex;
  gap: 24px;
  margin-bottom: 32px;
  padding: 24px;
  background: linear-gradient(
    135deg,
    rgba(115, 103, 240, 0.05) 0%,
    rgba(115, 103, 240, 0.02) 100%
  );
  border-radius: 12px;
  border: 1px solid rgba(115, 103, 240, 0.1);

  .search-item {
    display: flex;
    align-items: center;
    gap: 12px;

    .search-label {
      font-weight: 500;
      color: #1e1e2d;
    }

    .search-input {
      width: 260px;

      :deep(.el-input__wrapper) {
        box-shadow: 0 2px 12px rgba(115, 103, 240, 0.1);
        border-radius: 8px;
        padding: 0 16px;
        background: rgba(255, 255, 255, 0.9);

        &:hover {
          box-shadow: 0 4px 16px rgba(115, 103, 240, 0.15);
        }

        &.is-focus {
          box-shadow: 0 0 0 2px rgba(115, 103, 240, 0.2);
        }
      }
    }
  }
}

.team-list {
  :deep(.el-table) {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 24px rgba(115, 103, 240, 0.08);

    th {
      background-color: #f8f8fb !important;
      color: #1e1e2d;
      font-weight: 600;
      padding: 16px;
    }

    td {
      padding: 16px;
      color: #6e6b7b;
    }

    .el-button {
      padding: 8px 16px;
      font-weight: 500;
      transition: all 0.3s ease;

      &--primary {
        color: #7367f0;

        &:hover {
          color: #9f94ff;
          transform: translateX(4px);
        }
      }
    }
  }
}

.pagination-container {
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;

  :deep(.el-pagination) {
    justify-content: flex-end;

    .el-pagination__total {
      margin-right: 16px;
    }

    .el-pagination__sizes {
      margin-right: 16px;
    }

    .btn-prev,
    .btn-next {
      background: #ffffff;
      border: 1px solid #e0e0e0;
      border-radius: 6px;
      padding: 0 12px;
      margin: 0 4px;
      height: 32px;

      &:hover {
        color: #7367f0;
        border-color: #7367f0;
      }
    }

    .el-pager li {
      background: #ffffff;
      border: 1px solid #e0e0e0;
      border-radius: 6px;
      margin: 0 4px;
      min-width: 32px;
      height: 32px;
      line-height: 32px;

      &:hover {
        color: #7367f0;
        border-color: #7367f0;
      }

      &.is-active {
        background: #7367f0;
        color: #ffffff;
        border-color: #7367f0;
      }
    }
  }
}

:deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 32px rgba(115, 103, 240, 0.15);

  .el-dialog__header {
    margin: 0;
    padding: 20px 24px;
    border-bottom: 1px solid #f0f0f0;

    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #1e1e2d;
    }
  }

  .el-dialog__body {
    padding: 24px;
  }

  .el-dialog__footer {
    border-top: 1px solid #f0f0f0;
    padding: 16px 24px;
  }

  .el-button {
    padding: 10px 24px;
    border-radius: 8px;
    transition: all 0.3s ease;

    &--primary {
      background: linear-gradient(135deg, #7367f0 0%, #9f94ff 100%);
      border: none;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(115, 103, 240, 0.3);
      }
    }
  }

  .el-textarea__inner {
    border-radius: 8px;
    padding: 12px;
    box-shadow: 0 2px 12px rgba(115, 103, 240, 0.1);
    border: 1px solid rgba(115, 103, 240, 0.1);

    &:hover {
      box-shadow: 0 4px 16px rgba(115, 103, 240, 0.15);
    }

    &:focus {
      box-shadow: 0 0 0 2px rgba(115, 103, 240, 0.2);
      border-color: #7367f0;
    }
  }
}
</style>
